import React, { useCallback, useMemo } from 'react';
import PropTypes from 'prop-types';
import './Radio.css';

function Radio(props) {
  const {
    disabled,
    checked,
    onChange,
    className,
    children,
    value,
    button,
    defaultValue,
  } = props;
  // console.log('radio ===> 渲染一次', children, defaultValue);

  // 单独使用 不用 radioGroup 包裹
  const aloneState = defaultValue && defaultValue === value;
  // 避免 group 更新带动子元素更新
  const element = useCallback(() => {
    // 拆分 button 样式和普通样式 方便维护
    if (!button) {
      return (
        <label className={`Radio_ant_radio_wrapper`}>
          <span
            className={`Radio_ant_radio ${
              checked || aloneState ? 'Radio_ant_radio_checked' : ''
            } ${className || ''}`}
          >
            <input type="radio" className="Radio_ant_radio_input" />
            <span className="Radio_ant_radio_inner"></span>
          </span>
          <span className="Radio_radio_label">{children}</span>
        </label>
      );
    } else {
      return (
        <label className={`Radio_ant_radio_wrapper ${className || ''}`}>
          <input type="radio" className="Radio_ant_radio_input" />
          <span className="Radio_radio_label_button">{children}</span>
        </label>
      );
    }
  }, [defaultValue,checked]);

  return (
    <div
      className={`Radio_ant ${button && 'RadioButton'}  ${
        disabled
          ? `${
              button ? 'Radio_ant_radio_button_disabled' : 'Radio_ant_radio_disabled'
            } Radio_disabled`
          : ''
      }  ${button && checked ? 'Radio_button_checked' : ''}`}
      onClick={(E) => !disabled && onChange && onChange(value, children)}
    >
      {element()}
    </div>
  );

}

// 类型检查
Radio.propTypes = {
  checked: PropTypes.bool,
  disabled: PropTypes.bool,
  onChange: PropTypes.func.isRequired,
  className: PropTypes.oneOfType([PropTypes.string]),
  children: PropTypes.oneOfType([PropTypes.string, PropTypes.element]),
};

// 入参默认值
Radio.defaultProps = {
  checked: false,
  disabled: false,
  button: false,
};

export default Radio;
